package com.dongnam.quanly.web;

import java.math.BigDecimal;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dongnam.quanly.web.util.LocaleMessages;
import com.sun.faces.util.MessageFactory;

/**
 * Currently, this validator supports BigDecimal only.
 */
@FacesValidator("com.dongnam.quanly.web.CurrencyValidator")
public class CurrencyValidator implements Validator {

	private static Logger logger = LoggerFactory.getLogger(CurrencyValidator.class);

	private int maxFractionDigits = 0;

	private boolean positiveOnly = false;

	@Override
	public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
		logger.debug("validate: value = {}", value);
		if (value instanceof BigDecimal) {
			BigDecimal number = (BigDecimal) value;
			try {
				number.setScale(maxFractionDigits);
			} catch (ArithmeticException e) {
				FacesMessage message = LocaleMessages.getMessage("validator_currency_maxFractionalDigits",
						MessageFactory.getLabel(context, component), maxFractionDigits);
				message.setSeverity(FacesMessage.SEVERITY_ERROR);
				throw new ValidatorException(message);
			}
			if (positiveOnly) {
				if (number.signum() < 0) {
					FacesMessage message = LocaleMessages.getMessage("validator_currency_positiveOnly",
							MessageFactory.getLabel(context, component));
					message.setSeverity(FacesMessage.SEVERITY_ERROR);
					throw new ValidatorException(message);
				}
			}
		}
	}

	public int getMaxFractionDigits() {
		return maxFractionDigits;
	}

	public void setMaxFractionDigits(int maxFractionDigits) {
		this.maxFractionDigits = maxFractionDigits;
	}

	public boolean isPositiveOnly() {
		return positiveOnly;
	}

	public void setPositiveOnly(boolean positiveOnly) {
		this.positiveOnly = positiveOnly;
	}

}
